package cn.hfjava.kz.controller;

import cn.dev33.satoken.util.SaResult;
import cn.hfjava.kz.config.OssConfig;
import cn.hfjava.kz.entity.dto.ExamAdmissionQueryDTO;
import cn.hfjava.kz.entity.excel.ExamAdmissionExcel;
import cn.hfjava.kz.entity.po.ExamAdmissionTicket;
import cn.hfjava.kz.entity.vo.PageVO;
import cn.hfjava.kz.listener.ExamAdmissionListener;
import cn.hfjava.kz.service.ExamAdmissionTicketService;
import com.alibaba.excel.EasyExcel;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 29264
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/exam")
@Tag(name = "准考生管理模块", description = "准考证管理模块接口")
public class ExamAdmissionController {

    private final ExamAdmissionTicketService examAdmissionService;
    private final ExamAdmissionTicketService examAdmissionTicketService;
    private final OssConfig ossConfig;


    @Operation(summary = "分页查询准考证信息")
    @PostMapping("/listPage")
    public SaResult listPage(@RequestBody ExamAdmissionQueryDTO examAdmissionQueryDto) {
       PageVO pageVO = examAdmissionService.findByPage(examAdmissionQueryDto);
       return SaResult.data(pageVO);
    }

    @Operation(summary = "导出承诺书信息")
    @PostMapping("/exportExamAdmission")
    public void exportExamAdmission(HttpServletResponse response) {
        OSSClient ossClient = ossConfig.ossClient();
        String bucketName = ossConfig.getBucketName();
        String objectName = "Templates/诚信考试承诺书（理论实操.docx";
        OSSObject object = ossClient.getObject(bucketName, objectName);
        XWPFDocument allDocument = new XWPFDocument();
        ByteArrayInputStream inputStream = null;
        List<ExamAdmissionTicket> allExam = examAdmissionTicketService.getAllExam();
        try {
            inputStream = new ByteArrayInputStream(object.getObjectContent().readAllBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        XWPFDocument xwpfDocument1 = null;
        try {
            xwpfDocument1 = new XWPFDocument(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        for(ExamAdmissionTicket examUserInfo:allExam) {
            //身份证信息
//            String idnum = examUserInfo.getIdNum();
//            //准考证信息
//            String seatnum = examUserInfo.getSeatNum();

//            actionDocument(xwpfDocument1,idnum,seatnum);
            mergeDocument(xwpfDocument1, allDocument);

        }
        int logo = 0;
        for(ExamAdmissionTicket examUserInfo:allExam) {
//            身份证信息
            String idnum = examUserInfo.getIdNum();
            //准考证信息
            String seatnum = examUserInfo.getSeatNum();

            actionDocument(allDocument,idnum,seatnum,logo);
//            mergeDocument(xwpfDocument1, allDocument);
            logo++;
        }

//        System.out.println(paragraphs.size());
//        System.out.println(tables.size());


        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            allDocument.write(out);
            allDocument.close(); // 关闭文档以释放资源

            // 设置响应的内容类型
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

            // 设置响应头以触发文件下载
            String fileName = "所有承诺书.docx";
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader(headerKey, headerValue);

            // 获取 ServletOutputStream 并写入文档内容
            ServletOutputStream servletOutputStream = response.getOutputStream();
            out.writeTo(servletOutputStream);
            servletOutputStream.flush();
            xwpfDocument1.close();
            allDocument.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    @GetMapping("/exportAllExecl")
    @Operation(summary = "导出所有准考证信息")
    public SaResult exportAllExecl(HttpServletResponse response) {
        // 设置response的header
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
//        OSSClient ossClient = ossConfig.ossClient();
//        String bucketName = ossConfig.getBucketName();
//        String objectName = "Templates/诚信考试承诺书（理论实操.docx";
//        OSSObject object = ossClient.getObject(bucketName, objectName);
        // 获取准考证数据
        List<ExamAdmissionExcel> examDataList =examAdmissionTicketService.selectAllExam();
        if (examDataList.isEmpty()) {
            return SaResult.error("没有找到准考证信息");
        }
        try {
            fileName = URLEncoder.encode("准考证信息", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            EasyExcel.write(outputStream, ExamAdmissionExcel.class)
                    .sheet("Sheet1")
                    .doWrite(examDataList);
            return SaResult.ok("导出成功");
        } catch (IOException e) {
            return SaResult.error("导出失败");
        }
    }
    @PostMapping("exportExcel")
    @Operation(summary = "根据id导出excel")
    public SaResult exportExcel(@RequestBody List<Integer> idList, HttpServletResponse response) {
        // 设置response的header
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
//        OSSClient ossClient = ossConfig.ossClient();
//        String bucketName = ossConfig.getBucketName();
//        String objectName = "Templates/诚信考试承诺书（理论实操.docx";
//        OSSObject object = ossClient.getObject(bucketName, objectName);
        // 获取准考证数据
        List<ExamAdmissionExcel> examDataList =examAdmissionTicketService.findStudentExcelByIdList(idList);
        if (examDataList.isEmpty()) {
            return SaResult.error("没有找到准考证信息");
        }
        try {
            fileName = URLEncoder.encode("准考证信息", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            EasyExcel.write(outputStream, ExamAdmissionExcel.class)
                    .sheet("Sheet1")
                    .doWrite(examDataList);
            return SaResult.ok("导出成功");
        } catch (IOException e) {
            return SaResult.error("导出失败");
        }
//        // 使用EasyExcel写数据到response的输出流中
//        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(object.getObjectContent().readAllBytes());) {
//            // 创建ExcelWriter
//            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
//                    .withTemplate(inputStream)
//                    .build();
//
//            // 创建写入sheet
//            WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1")
//                    .build();
//
//            // 写入数据，不包含表头
//            excelWriter.write(examDataList, writeSheet);
//            excelWriter.finish();
//        } catch (IOException e) {
//            return SaResult.error("导出失败");
//        }
    }
    @PostMapping(name = "importExcel",consumes = "multipart/form-data")
    @Operation(summary = "导入excel")
    public SaResult importExcel(@RequestPart(name = "file", required = true) MultipartFile file) {
        try {

            // 读取Excel文件
            EasyExcel.read(file.getInputStream(), ExamAdmissionExcel.class, new ExamAdmissionListener(examAdmissionTicketService))
                    .headRowNumber(1) // 设置跳过第一行
                    .sheet()
                    .doRead();
//            List<DataModel> list = EasyExcel.read(fileName, DataModel.class, new ReadListener<DataModel>() {
//                @Override
//                public void invoke(DataModel data, AnalysisContext context) {
//                    // 处理读取到的每一行数据
//                    System.out.println(data.getDateTime());
//                }
//
//                @Override
//                public void doAfterAllAnalysed(AnalysisContext context) {
//                    // 所有数据解析完成后的操作
//                }
//            }).sheet().doRead();
            // 处理读取到的数据...
            // 这里只是简单地将读取到的数据数量作为响应返回
            return SaResult.ok("读取成功");
        } catch (IOException e) {
            e.printStackTrace();
            return SaResult.error("读取失败");
        }

    }
    public void mergeDocument(XWPFDocument sourceDocument, XWPFDocument mainDocument) {
        // 复制段落

        // 复制段落
        List<XWPFParagraph> paragraphs = sourceDocument.getParagraphs();
        List<XWPFTable> tables = sourceDocument.getTables();

//        System.out.println(paragraphs.size());
        for(int i = 0;i < 7;i++) {
            XWPFParagraph paragraph = paragraphs.get(i);
            XWPFParagraph newParagraph = mainDocument.createParagraph();
            newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
            newParagraph.createRun().setText(paragraph.getText());
        }
        for (int n = 0; n < 1; n++) {
            XWPFTable table = tables.get(n);
            XWPFTable newTable = mainDocument.createTable(table.getNumberOfRows(), table.getRow(0).getTableCells().size());
            for (int i = 0; i < table.getNumberOfRows(); i++) {
                for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {
                    XWPFTableCell newCell = newTable.getRow(i).getCell(j);
                    XWPFTableCell sourceCell = table.getRow(i).getCell(j);
                    newCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
                    newCell.setText(sourceCell.getText());
                    setCellParagraphsCenter(newCell);
                }
            }
        }
        for(int i = 7;i < 9;i++) {
            XWPFParagraph paragraph = paragraphs.get(i);
            XWPFParagraph newParagraph = mainDocument.createParagraph();
            newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
            newParagraph.createRun().setText(paragraph.getText());
        }
        for(int n = 1; n < 2; n++) {
            XWPFTable table = tables.get(n);
            XWPFTable newTable = mainDocument.createTable(table.getNumberOfRows(), table.getRow(0).getTableCells().size());
            for (int i = 0; i < table.getNumberOfRows(); i++) {
                for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {
                    XWPFTableCell newCell = newTable.getRow(i).getCell(j);
                    XWPFTableCell sourceCell = table.getRow(i).getCell(j);
                    newCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
                    newCell.setText(sourceCell.getText());
                    setCellParagraphsCenter(newCell);
                }
            }
        }
        for(int i = 9;i < 20;i++) {
            XWPFParagraph paragraph = paragraphs.get(i);
            XWPFParagraph newParagraph = mainDocument.createParagraph();
            newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
            newParagraph.createRun().setText(paragraph.getText());
        }
        for(int n = 2; n < 3; n++) {
            XWPFTable table = tables.get(n);
            XWPFTable newTable = mainDocument.createTable(table.getNumberOfRows(), table.getRow(0).getTableCells().size());
            for (int i = 0; i < table.getNumberOfRows(); i++) {
                for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {
                    XWPFTableCell newCell = newTable.getRow(i).getCell(j);
                    XWPFTableCell sourceCell = table.getRow(i).getCell(j);
                    newCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
                    newCell.setText(sourceCell.getText());
                    setCellParagraphsCenter(newCell);
                }
            }
        }
        for(int i = 20;i < 22;i++) {
            XWPFParagraph paragraph = paragraphs.get(i);
            XWPFParagraph newParagraph = mainDocument.createParagraph();
            newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
            newParagraph.createRun().setText(paragraph.getText());
        }
        for(int n = 3; n < 4; n++) {
            XWPFTable table = tables.get(n);
            XWPFTable newTable = mainDocument.createTable(table.getNumberOfRows(), table.getRow(0).getTableCells().size());
            for (int i = 0; i < table.getNumberOfRows(); i++) {
                for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {
                    XWPFTableCell newCell = newTable.getRow(i).getCell(j);
                    XWPFTableCell sourceCell = table.getRow(i).getCell(j);
                    newCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
                    newCell.setText(sourceCell.getText());
                    setCellParagraphsCenter(newCell);

                }
            }
        }
        for(int i = 22;i < 25;i++) {
            XWPFParagraph paragraph = paragraphs.get(i);
            XWPFParagraph newParagraph = mainDocument.createParagraph();
            newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
            newParagraph.createRun().setText(paragraph.getText());
        }
        for(int i = 1; i < 5; i++) {
            // 创建一个新的段落
            XWPFParagraph paragraph = mainDocument.createParagraph();

            // 创建一个新的Run对象（文本运行）
            XWPFRun run = paragraph.createRun();
        }

//        for (XWPFParagraph paragraph : sourceDocument.getParagraphs()) {
//            XWPFParagraph newParagraph = mainDocument.createParagraph();
//            newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
//            newParagraph.createRun().setText(paragraph.getText());
//        }
//
//
//        // 复制表格
//        for (XWPFTable table : sourceDocument.getTables()) {
//
//            XWPFTable newTable = mainDocument.createTable(table.getNumberOfRows(), table.getRow(0).getTableCells().size());
//            for (int i = 0; i < table.getNumberOfRows(); i++) {
//                for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {
//                    XWPFTableCell newCell = newTable.getRow(i).getCell(j);
//                    XWPFTableCell sourceCell = table.getRow(i).getCell(j);
//                    newCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
//                    newCell.addParagraph().createRun().setText(sourceCell.getText());
//                }
//            }
//        }
    }
    public void actionDocument(XWPFDocument document, String idnum, String seatnum,Integer logo){
        List<XWPFTable> tables = document.getTables();
        ArrayList<XWPFTable> xwpfTables = new ArrayList<>();
        ArrayList<XWPFTable> xwpfTables1 = new ArrayList<>();
        xwpfTables.add(tables.get(logo*4));
        xwpfTables.add(tables.get(logo*4+2));
        xwpfTables1.add(tables.get(logo*4+1));
        xwpfTables1.add(tables.get(logo*4+3));
        for (XWPFTable table : xwpfTables){
            int num2 = 0;
            for (XWPFTableRow row : table.getRows()) {

                for (XWPFTableCell cell : row.getTableCells()) {
                    List<XWPFTableCell> tableCells = row.getTableCells();
                    System.out.println(tableCells.size());
//                        xwpfTableCells.add(cell);

                    if (num2 < seatnum.length()) {
                        cell.setText(seatnum.charAt(num2) + "");
                        setCellParagraphsCenter(cell);
                        num2++;
                    } else {
                        cell.setText("");
                    }
                }

            }
        }
        for (XWPFTable table : xwpfTables1){
            for (XWPFTableRow row : table.getRows()) {
                List<XWPFTableRow> rows = table.getRows();
//                    System.out.println(rows.size());
                int num1 = 0;
                for (XWPFTableCell cell : row.getTableCells()) {
                    List<XWPFTableCell> tableCells = row.getTableCells();
//                        System.out.println(tableCells.size());
                    if (num1 < idnum.length()) {
                        cell.setText(idnum.charAt(num1) + "");
                        setCellParagraphsCenter(cell);
                        num1++;
                    } else {
                        cell.setText("");
                    }
                }
            }
        }



//                ArrayList<XWPFTableCell> xwpfTableCells = new ArrayList<>();

//                for (XWPFTableCell cell : xwpfTableCells) {
//                    if (num2 < seatnum.length()) {
//                        cell.setText(seatnum.charAt(num2) + "");
//                        setCellParagraphsCenter(cell);
//                        num2++;
//                    } else {
//                        cell.setText("");
//                    }
//
//                }
    }
    public void setCellParagraphsCenter(XWPFTableCell cell) {
        // 遍历单元格中的所有段落
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            // 设置段落的对齐方式为居中
            paragraph.setAlignment(ParagraphAlignment.CENTER);
        }
    }


}
